package dream.servlet;

import com.alibaba.fastjson.JSONObject;
import dream.service.OperateService;
import lombok.SneakyThrows;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

/**
 * 提交申报名表的Servlet
 */
@WebServlet("/get_in_touch")
public class GetInTouchServlet extends HttpServlet {
    private OperateService operateService = new OperateService();

    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //设置编码格式为UTF-8
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html");

        //获取表单提交参数
        String name = req.getParameter("name");
        String email = req.getParameter("email");
        String session = req.getParameter("session");
        String message = req.getParameter("message");
        String captcha_code = req.getParameter("captcha_code");
        String token = (String) req.getSession().getAttribute("captcha");

        //使用json回传json对象
        JSONObject object = new JSONObject();

        //判断输入数据是否合法
        if (name.equals("") || email.equals("") || message.equals("") || captcha_code.equals("")) {

            //放入json信息
            object.put("responseWord", "输入框不能为空！");
            object.put("consequence", 0);

        } else if (name.matches("^([\u4e00-\u9fa5]+){1,8}$")==false) {

            object.put("responseWord", "姓名为中文1~8位！");
            object.put("consequence", 0);

        } else if (email.matches("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$")==false) {

            object.put("responseWord", "邮箱格式错误！");
            object.put("consequence", 0);

        } else if (token.toUpperCase().equals(captcha_code)==false) {

            req.getSession().removeAttribute("captcha");//删除当前验证码的值
            object.put("responseWord", "验证码错误！");
            object.put("consequence", 0);

        } else {
            //保存报名用户到数据库
            operateService.InsertSignUpPojo(name, email, Integer.parseInt(session), message, new Date().getTime());
            //放入json信息
            object.put("responseWord", "报名成功！");
            object.put("consequence", 1);
            new SendEmail(name, email);
        }

        //回传json对象
        resp.getWriter().print(object);

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
